package com.itbz.servlet;

import com.google.gson.Gson;
import com.itbz.pojo.Score;
import com.itbz.service.Impl.ScoreServiceImpl;
import com.itbz.service.ScoreService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/www/ScoreServlet")
public class ScoreServlet extends HttpServlet {
    private ScoreService scoreService=new ScoreServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");
        if("save".equals(method)){
            save(req,resp);
        } else if ("findAll".equals(method)) {
            findAll(req,resp);
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //2.根据数据返回结果
        List<Score> allSelect = scoreService.allFind();
        //3.根据结果给响应
        String json = new Gson().toJson(allSelect);
        resp.getWriter().println(json);
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.接收前端数据
        String sname = req.getParameter("sname");
        int first = Integer.parseInt(req.getParameter("first"));
        int second = Integer.parseInt(req.getParameter("second"));
        int srid = Integer.parseInt(req.getParameter("srid"));
        Score score=new Score(sname,first,second,srid);
        //2.根据数据返回结果
        int add = scoreService.insertAdd(score);
        //3.根据结果给用户响应
        resp.getWriter().println(add);
    }
}
